import axios from "axios";
// 创建axios实例
const service = axios.create({
    baseURL: "/apix",
    timeout: 5000 // 请求超时时间
});


// request拦截器
service.interceptors.request.use(
    config => {
        return new Promise(resolve => {
            resolve(config);
        });
    },
    error => {
        // Do something with request error
        Promise.reject(error);
    }
);

// respone拦截器
service.interceptors.response.use(
    response => {
        const data = response.data;
        console.log(data, 'data')
        return Promise.resolve(data)
    },
    error => {
        let data = JSON.parse(JSON.stringify(error))
        // Do something with request error
        console.log(error, "error")
        Promise.reject(error);
    }
);

export function fetch(url, data, method = 'GET', headers = {}) {
    return new Promise((resolve, reject) => {
        let options = {
            'method': method,
            'url': url,
            'headers': headers && typeof headers === 'object' ? headers : {}
        }
        options.headers['X-Requested-Page'] = 'json'
        options[method === 'GET' ? 'params' : 'data'] = data
        service(options).then((response) => {
            resolve(response)
        }).catch((error) => {
            reject(error)
        })
    })
}

export default fetch;
